﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DocumentRelationsDataType.ascx.cs" company="Vizioz Limited">
//   Copyright 2011
// </copyright>
// <summary>
//  Document relation user control used to build the data type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System.Web.UI;

[assembly: WebResource("Vizioz.Relationships.css.flags16.css", "text/css", PerformSubstitution = true)]
[assembly: WebResource("Vizioz.Relationships.images.flags16.png", "image/png")]

namespace Vizioz.Relationships.UserControls
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Text;
    using System.Text.RegularExpressions;

    using ClientDependency.Core;

    using umbraco.cms.businesslogic.relation;

    /// <summary>
    /// User control user to build the Document Relation data type.
    /// </summary>
    public partial class DocumentRelationsDataType : UserControl, umbraco.editorControls.userControlGrapper.IUsercontrolDataEditor
    {       
        /// <summary>
        /// Gets or sets the umbraco value.
        /// </summary>
        /// <value>Umbraco value.</value>
        [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Property from umbraco interface")]
        public object value { get; set; }

        /// <summary>
        /// Get the node's domains
        /// </summary>
        /// <param name="nodeId">
        /// The node Id.
        /// </param>
        /// <returns>
        /// A culture string
        /// </returns>
        public static umbraco.cms.businesslogic.language.Language GetNodePrimaryLanguage(int nodeId)
        {
            var domains = umbraco.library.GetCurrentDomains(nodeId);

            if (domains == null || domains.Length == 0 || domains[0].Language == null)
            {
                return null;
            }

            return domains[0].Language;
        }
        
        /// <summary>
        /// Save the related documents.
        /// </summary>
        public void SaveRelatedDocuments()
        {
            var documentId = int.Parse(Request.QueryString["id"]);
            var regexId = new Regex("document_picker_(?<id>[0-9]+)_ContentIdValue", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);

            foreach (var key in Request.Form.AllKeys)
            {
                if (key != null)
                {
                    var match = regexId.Match(key);
                    if (match.Success)
                    {
                        var prevId = int.Parse(match.Groups["id"].Value);
                        int nextId;
                        int.TryParse(Request.Form[string.Format("document_picker_{0}_ContentIdValue", prevId)], out nextId);

                        if (prevId == nextId)
                        {
                            continue;
                        }

                        if (nextId == 0)
                        {
                            // DELETE RELATION
                            var relations = Relation.GetRelations(prevId);
                            foreach (var relation in relations)
                            {
                                if (relation.Parent.Id == documentId || relation.Child.Id == documentId)
                                {
                                    relation.Delete();
                                }
                            }
                        }
                        else if (prevId == 0)
                        {
                            // ADD RELATION
                            Relation.MakeNew(documentId, nextId, RelationType.GetByAlias("relateDocumentOnCopy"), string.Empty);
                        }
                        else
                        {
                            // DELETE RELATION
                            var relations = Relation.GetRelations(prevId);
                            foreach (var relation in relations)
                            {
                                if (relation.Parent.Id == documentId || relation.Child.Id == documentId)
                                {
                                    relation.Delete();
                                }
                            }

                            // ADD RELATION
                            Relation.MakeNew(documentId, nextId, RelationType.GetByAlias("relateDocumentOnCopy"), string.Empty);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Get related documents.
        /// </summary>
        /// <returns>Related documents.</returns>
        public string GetRelatedDocuments()
        {
            var documentId = int.Parse(Request.QueryString["id"]);
            var relations = umbraco.library.GetRelatedNodes(documentId);

            var strHtml = new StringBuilder();
            strHtml.Append("<ul style='list-style: none; margin-left: 0px; padding-left: 0px;' class='f16'>");

            if (relations.Length != 0)
            {
                foreach (var relation in relations)
                {
                    if (relation.Child.Id == documentId)
                    {
                        strHtml.Append(GetRelatedDocument(relation.Parent.Id, relation.Parent.Text));
                    }

                    if (relation.Parent.Id == documentId)
                    {
                        strHtml.Append(GetRelatedDocument(relation.Child.Id, relation.Child.Text));
                    }
                }
            }

            if (System.Configuration.ConfigurationManager.AppSettings["ViziozNumberOfRelationships"] != null)
            {
                var viziozNumberOfRelationships = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ViziozNumberOfRelationships"]);

                if (viziozNumberOfRelationships > relations.Length)
                {
                    strHtml.Append(GetRelatedDocument(0, "Add a new relationship"));
                }
            }
            else
            {
                // If there is no maximum, allow additional relationships to be added.
                strHtml.Append(GetRelatedDocument(0, "Add a new relationship"));
            }

            strHtml.Append("</ul>");

            return strHtml.ToString();
        }

        /// <summary>
        /// Page Load event.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The event arguments.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                this.SaveRelatedDocuments();
            }

            this.AddResourceToClientDependency("Vizioz.Relationships.css.flags16.css", ClientDependencyType.Css);            
        }   

        /// <summary>
        /// Get related document interface.
        /// </summary>        
        /// <param name="nodeId">Node identifier.</param>
        /// <param name="nodeTitle">Node title text.</param>
        /// <returns>Related document html interace.</returns>
        private static StringBuilder GetRelatedDocument(int nodeId, string nodeTitle)
        {
            var strHtml = new StringBuilder();

            strHtml.Append("<li class='flag");
            if (nodeId != 0)
            {
                var language = GetNodePrimaryLanguage(nodeId);

                if (language != null)
                {
                    var culture = language.CultureAlias;
                
                    var country = culture.Substring(culture.IndexOf("-") + 1);

                    if (country.Length > 0)
                    {
                        strHtml.Append(" " + country.ToLower() + "'");
                        strHtml.Append(" title='" + language.FriendlyName + "'");
                    }
                    else
                    {
                        strHtml.Append("'");
                    }
                }
                else
                {
                    strHtml.Append("'");
                }
            }
            else
            {
                strHtml.Append("'");
            }

            strHtml.Append(">");

            strHtml.Append(
                string.Format("<input type='hidden' name='document_picker_{0}_ContentIdValue' id='document_picker_{0}_ContentIdValue' value='{0}' />", nodeId));
            strHtml.Append(
                nodeId == 0
                    ? string.Format("<span id='document_picker_{0}_btns' style='display: none;'>", nodeId)
                    : string.Format("<span id='document_picker_{0}_btns'>", nodeId));

            strHtml.Append(string.Format("<span id='document_picker_{0}_title' style='font-weight:bold; text-decoration: underline; cursor: pointer;' onclick=\"location.href='/umbraco/editContent.aspx?id={0}'\">{1}</span>&nbsp;&nbsp;", nodeId, nodeTitle));
            strHtml.Append(
                string.Format(
                    "<a href='javascript:mc_document_picker_{0}.ClearSelection();' onclick=\"javascript:this.parentNode.parentNode.className='flag';\" style='color:red;' title='Delete'>Delete</a>&nbsp;&nbsp;", nodeId));
            strHtml.Append("</span>");
            strHtml.Append(string.Format("<a href='javascript:mc_document_picker_{0}.LaunchPicker();'>Choose...</a>", nodeId));
            strHtml.Append("<script type='text/javascript'>");
            strHtml.Append(
                string.Format("var mc_document_picker_{0} = new Umbraco.Controls.TreePicker('document_picker_{0}','Choose Content','document_picker_{0}_ContentIdValue','document_picker_{0}_title','/umbraco/dialogs/treepicker.aspx?rnd={1}&id={0}&treeType=content&contextMenu=true&isDialog=false&app=content',320,400,true,'/umbraco');", nodeId, DateTime.Now.Ticks));
            strHtml.Append("</script>");                              
            strHtml.Append("</li>");

            return strHtml;
        }
    }
}